package com.siyoumi.app.modules.wechat.service;

import com.siyoumi.app.modules.wechat.entity.WechatGroupChatUser;
import com.siyoumi.app.modules.wechat.entity.WechatNotifyData;
import com.siyoumi.component.XApp;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

//群抽奖
@Slf4j
@Service
public class WeChatEventChou
        implements WechatEvent {
    static public WeChatEventChou getBean() {
        return XSpringContext.getBean(WeChatEventChou.class);
    }

    @Override
    public XReturn handle(WechatNotifyData data) {
        //抽奖
        chouBegin(data);
        chouSign(data);
        chouEnd(data);

        return null;
    }

    public Boolean exists(String roomId) {
        return XRedis.getBean().exists(WeChatUtil.getKeyChou(roomId));
    }

    /**
     * 抽奖开始
     *
     * @param data
     */
    public void chouBegin(WechatNotifyData data) {
        if (!data.getIs_at()) {
            return;
        }
        if (!data.getContent().contains("群抽奖")) {
            return;
        }

        WechatOpenApi api = WechatOpenApi.getIns();

        String roomId = data.getRoomid();
        if (exists(roomId)) {
            api.sendTxt(roomId, "抽奖进行中", "");
            return;
        }

        String msg = "抽奖开始\n报名输入: 【1】\n结束输入: 【抽奖+人数】，例: 抽奖2人";
        api.sendTxt(roomId, msg, "");

        String redisKey = WeChatUtil.getKeyChou(roomId);
        RMap<String, String> list = XRedis.getBean().getList(redisKey);
        list.put(data.getSender(), "1");
    }

    /**
     * 报名
     *
     * @param data
     */
    public void chouSign(WechatNotifyData data) {
        if (XStr.isNullOrEmpty(data.getContent())) {
            return;
        }
        if (!"1".equals(data.getContent())) {
            return;
        }

        if (!exists(data.getRoomid())) {
            //没有开始抽奖
            return;
        }

        String redisKey = WeChatUtil.getKeyChou(data.getRoomid());
        RMap<String, String> list = XRedis.getBean().getList(redisKey);
        list.put(data.getSender(), "1");
    }

    /**
     * 抽奖结束
     *
     * @param data
     */
    public void chouEnd(WechatNotifyData data) {
        String msg = data.getContent();
        String roomId = data.getRoomid();

        if (XStr.isNullOrEmpty(msg)
                || !XStr.startsWith(msg, "抽奖")) {
            return;
        }
        // 创建将用于匹配数字的正则表达式对象
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(msg);
        if (!matcher.find()) {
            return;
        }
        int chouCount = XStr.toInt(matcher.group());
        log.info("抽奖数量: {}", chouCount);

        if (!exists(roomId)) {
            log.info("没有开始抽奖");
            return;
        }

        WechatOpenApi api = WechatOpenApi.getIns();

        String redisKey = WeChatUtil.getKeyChou(roomId);
        RMap<String, String> list = XRedis.getBean().getList(redisKey);
        if (list.size() <= 0) {
            api.sendTxt(roomId, "暂无人报名", "");
            return;
        }
        if (list.size() < chouCount) {
            api.sendTxt(roomId, "抽奖人数不足" + chouCount, "");
            return;
        }

        List<WechatGroupChatUser> listUser = api.groupchatUser(roomId);
        List<WechatGroupChatUser> listUserChou = new ArrayList<>();
        for (Map.Entry<String, String> entry : list.entrySet()) {
            //获取群用户名称
            WechatGroupChatUser chatUser = listUser.stream().filter(v ->
                    v.getId().equals(entry.getKey())).findFirst().orElse(null);

            listUserChou.add(chatUser);
        }

        //抽奖
        List<Integer> winList = new ArrayList<>();
        while (winList.size() < chouCount) {
            int rnd = XApp.random(0, chouCount - 1);
            if (winList.contains(rnd)) {
                continue;
            }

            winList.add(rnd);
        }

        StringBuilder sb = new StringBuilder();
        sb.append("报名名单\n\n");
        int signIndex = 1;
        for (WechatGroupChatUser chatUser : listUserChou) {
            sb.append(signIndex + ": " + chatUser.getName() + "\n");
            signIndex++;
        }

        //中奖名单
        List<WechatGroupChatUser> listUserWin = new ArrayList<>();
        for (Integer index : winList) {
            WechatGroupChatUser chatUser = listUserChou.get(index);
            listUserWin.add(chatUser);
        }
        sb.append("\n中奖者: " + listUserWin.stream().map(item -> item.getName()).collect(Collectors.joining(",")));

        api.sendTxt(roomId, sb.toString(), "");

        XRedis.getBean().del(WeChatUtil.getKeyChou(roomId));
    }
}
